<script setup>
import { onMounted, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElCard, ElButton, ElTag, ElLoading, ElInput, ElSelect, ElOption, ElDialog, ElForm, ElFormItem, ElDatePicker, ElTimePicker } from 'element-plus'

const router = useRouter()

// 响应式数据
const departments = ref([])
const doctors = ref([])
const currentDepartment = ref(null)
const loading = ref(false)
const searchKeyword = ref('')
const appointmentDialogVisible = ref(false)
const selectedDoctor = ref(null)

// 预约表单
const appointmentForm = reactive({
  patientName: '',
  patientPhone: '',
  appointmentDate: '',
  appointmentTime: '',
  symptoms: '',
  remarks: ''
})

// 模拟科室数据
const mockDepartments = [
  { id: 1, name: '内科', description: '内科疾病诊治', icon: '' },
  { id: 2, name: '外科', description: '外科手术治疗', icon: '' },
  { id: 3, name: '妇产科', description: '妇科产科服务', icon: '👩' },
  { id: 4, name: '儿科', description: '儿童疾病诊治', icon: '' },
  { id: 5, name: '眼科', description: '眼部疾病治疗', icon: '👁️' },
  { id: 6, name: '口腔科', description: '口腔疾病治疗', icon: '🦷' },
  { id: 7, name: '皮肤科', description: '皮肤疾病诊治', icon: '👩‍⚕️' },
  { id: 8, name: '中医科', description: '中医诊疗服务', icon: '' },
  { id: 9, name: '急诊科', description: '急诊医疗服务', icon: '🚨' },
  { id: 10, name: '康复科', description: '康复理疗服务', icon: '🏃' }
]

// 模拟医生数据
const mockDoctors = {
  1: [ // 内科
    { id: 1, name: '张医生', title: '主任医师', department: '内科', experience_years: 15, rating: 4.8, avatar: 'https://via.placeholder.com/80x80/4CAF50/ffffff?text=张', specialties: ['心血管', '高血压'], introduction: '擅长心血管疾病诊治', consultation_fee: 50, is_featured: true },
    { id: 2, name: '李医生', title: '副主任医师', department: '内科', experience_years: 12, rating: 4.6, avatar: 'https://via.placeholder.com/80x80/2196F3/ffffff?text=李', specialties: ['消化内科', '胃病'], introduction: '消化内科专家', consultation_fee: 40, is_featured: false },
    { id: 3, name: '王医生', title: '主治医师', department: '内科', experience_years: 8, rating: 4.5, avatar: 'https://via.placeholder.com/80x80/FF9800/ffffff?text=王', specialties: ['呼吸内科', '哮喘'], introduction: '呼吸内科专业医生', consultation_fee: 30, is_featured: false }
  ],
  2: [ // 外科
    { id: 4, name: '陈医生', title: '主任医师', department: '外科', experience_years: 20, rating: 4.9, avatar: 'https://via.placeholder.com/80x80/9C27B0/ffffff?text=陈', specialties: ['普外科', '微创手术'], introduction: '外科手术专家', consultation_fee: 60, is_featured: true },
    { id: 5, name: '刘医生', title: '副主任医师', department: '外科', experience_years: 14, rating: 4.7, avatar: 'https://via.placeholder.com/80x80/E91E63/ffffff?text=刘', specialties: ['骨科', '关节'], introduction: '骨科专业医生', consultation_fee: 45, is_featured: false }
  ],
  3: [ // 妇产科
    { id: 6, name: '赵医生', title: '主任医师', department: '妇产科', experience_years: 18, rating: 4.8, avatar: 'https://via.placeholder.com/80x80/FF5722/ffffff?text=赵', specialties: ['妇科', '产科'], introduction: '妇产科专家', consultation_fee: 55, is_featured: true },
    { id: 7, name: '孙医生', title: '副主任医师', department: '妇产科', experience_years: 13, rating: 4.6, avatar: 'https://via.placeholder.com/80x80/795548/ffffff?text=孙', specialties: ['妇科肿瘤', '不孕不育'], introduction: '妇科肿瘤专家', consultation_fee: 50, is_featured: false }
  ],
  4: [ // 儿科
    { id: 8, name: '周医生', title: '主任医师', department: '儿科', experience_years: 16, rating: 4.9, avatar: 'https://via.placeholder.com/80x80/607D8B/ffffff?text=周', specialties: ['小儿内科', '发育'], introduction: '儿科专家', consultation_fee: 45, is_featured: true },
    { id: 9, name: '吴医生', title: '主治医师', department: '儿科', experience_years: 10, rating: 4.5, avatar: 'https://via.placeholder.com/80x80/009688/ffffff?text=吴', specialties: ['小儿外科', '急诊'], introduction: '小儿外科医生', consultation_fee: 35, is_featured: false }
  ],
  5: [ // 眼科
    { id: 10, name: '郑医生', title: '主任医师', department: '眼科', experience_years: 17, rating: 4.7, avatar: 'https://via.placeholder.com/80x80/3F51B5/ffffff?text=郑', specialties: ['白内障', '青光眼'], introduction: '眼科手术专家', consultation_fee: 50, is_featured: true }
  ],
  6: [ // 口腔科
    { id: 11, name: '冯医生', title: '副主任医师', department: '口腔科', experience_years: 12, rating: 4.6, avatar: 'https://via.placeholder.com/80x80/8BC34A/ffffff?text=冯', specialties: ['口腔外科', '种植牙'], introduction: '口腔外科专家', consultation_fee: 40, is_featured: false }
  ],
  7: [ // 皮肤科
    { id: 12, name: '韩医生', title: '主治医师', department: '皮肤科', experience_years: 9, rating: 4.4, avatar: 'https://via.placeholder.com/80x80/CDDC39/ffffff?text=韩', specialties: ['皮肤病', '美容'], introduction: '皮肤科专业医生', consultation_fee: 30, is_featured: false }
  ],
  8: [ // 中医科
    { id: 13, name: '杨医生', title: '主任医师', department: '中医科', experience_years: 25, rating: 4.9, avatar: 'https://via.placeholder.com/80x80/FFC107/ffffff?text=杨', specialties: ['中医内科', '针灸'], introduction: '中医专家', consultation_fee: 60, is_featured: true }
  ],
  9: [ // 急诊科
    { id: 14, name: '朱医生', title: '副主任医师', department: '急诊科', experience_years: 15, rating: 4.8, avatar: 'https://via.placeholder.com/80x80/F44336/ffffff?text=朱', specialties: ['急诊医学', '重症'], introduction: '急诊科专家', consultation_fee: 45, is_featured: true }
  ],
  10: [ // 康复科
    { id: 15, name: '秦医生', title: '主治医师', department: '康复科', experience_years: 11, rating: 4.5, avatar: 'https://via.placeholder.com/80x80/673AB7/ffffff?text=秦', specialties: ['康复治疗', '理疗'], introduction: '康复科专业医生', consultation_fee: 35, is_featured: false }
  ]
}

// 获取科室列表
async function fetchDepartments() {
  try {
    departments.value = mockDepartments
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 获取科室医生列表
async function fetchDoctorsByDepartment(departmentId) {
  loading.value = true
  try {
    setTimeout(() => {
      doctors.value = mockDoctors[departmentId] || []
      currentDepartment.value = departments.value.find(dept => dept.id === departmentId)
      loading.value = false
      if (doctors.value.length > 0) {
        ElMessage.success(`已加载 ${doctors.value.length} 位医生`)
      } else {
        ElMessage.warning('该科室暂无医生信息')
      }
    }, 500)
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
    loading.value = false
  }
}

// 搜索医生
function searchDoctors() {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  const allDoctors = Object.values(mockDoctors).flat()
  const filteredDoctors = allDoctors.filter(doctor => 
    doctor.name.toLowerCase().includes(keyword) ||
    doctor.specialties.some(specialty => specialty.toLowerCase().includes(keyword)) ||
    doctor.department.toLowerCase().includes(keyword)
  )
  
  doctors.value = filteredDoctors
  currentDepartment.value = { name: '搜索结果', description: `搜索"${searchKeyword.value}"的结果` }
  
  if (filteredDoctors.length > 0) {
    ElMessage.success(`找到 ${filteredDoctors.length} 位相关医生`)
  } else {
    ElMessage.warning('未找到相关医生')
  }
}

// 选择科室
function selectDepartment(department) {
  currentDepartment.value = department
  fetchDoctorsByDepartment(department.id)
}

// 预约医生
function makeAppointment(doctor) {
  selectedDoctor.value = doctor
  appointmentDialogVisible.value = true
  
  // 重置表单
  Object.assign(appointmentForm, {
    patientName: '',
    patientPhone: '',
    appointmentDate: '',
    appointmentTime: '',
    symptoms: '',
    remarks: ''
  })
}

// 提交预约
function submitAppointment() {
  if (!appointmentForm.patientName || !appointmentForm.patientPhone || !appointmentForm.appointmentDate) {
    ElMessage.warning('请填写必要信息')
    return
  }
  
  ElMessage.success(`预约成功！已为您预约${selectedDoctor.value.name}医生`)
  appointmentDialogVisible.value = false
  
  console.log('预约信息:', {
    doctor: selectedDoctor.value,
    form: appointmentForm
  })
}

// 返回首页
function goBack() {
  router.push('/home')
}

onMounted(() => {
  fetchDepartments()
})
</script>

<template>
  <div class="appointment-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content">
        <div class="logo">
          <el-button type="text" @click="goBack" class="back-btn">
            ← 返回首页
          </el-button>
          <h1>预约挂号</h1>
        </div>
        <div class="search-bar">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索医生、科室、疾病" 
            class="search-input"
            @keyup.enter="searchDoctors"
          >
            <template #append>
              <el-button type="primary" @click="searchDoctors">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 科室选择区域 -->
      <section class="departments-section">
        <div class="section-title">
          <h3>选择科室</h3>
          <p>请选择您要预约的科室</p>
        </div>
        <div class="departments-grid">
          <div
            v-for="department in departments"
            :key="department.id"
            class="department-item"
            :class="{ active: currentDepartment && currentDepartment.id === department.id }"
            @click="selectDepartment(department)"
          >
            <div class="department-icon">{{ department.icon }}</div>
            <div class="department-info">
              <span class="department-name">{{ department.name }}</span>
              <span class="department-desc">{{ department.description }}</span>
            </div>
          </div>
        </div>
      </section>

      <!-- 医生列表区域 -->
      <section v-if="currentDepartment" class="doctors-section">
        <div class="section-title">
          <h3>{{ currentDepartment.name }} - 医生列表</h3>
          <p class="section-subtitle">{{ currentDepartment.description }}</p>
        </div>
        
        <div v-loading="loading" class="doctors-grid">
          <el-card
            v-for="doctor in doctors"
            :key="doctor.id"
            class="doctor-card"
          >
            <div class="doctor-avatar">
              <img :src="doctor.avatar" :alt="doctor.name" />
            </div>
            <div class="doctor-info">
              <h4 class="doctor-name">{{ doctor.name }}</h4>
              <p class="doctor-title">{{ doctor.title }} · {{ doctor.department }}</p>
              <div class="doctor-stats">
                <el-tag size="small" type="success">经验 {{ doctor.experience_years }}年</el-tag>
                <el-tag size="small" type="warning">评分 {{ doctor.rating }}</el-tag>
                <el-tag v-if="doctor.is_featured" size="small" type="danger">推荐</el-tag>
              </div>
              <div class="doctor-specialties">
                <span v-for="specialty in doctor.specialties" :key="specialty" class="specialty-tag">
                  {{ specialty }}
                </span>
              </div>
              <div v-if="doctor.introduction" class="doctor-intro">
                <p>{{ doctor.introduction }}</p>
              </div>
              <div class="doctor-actions">
                <el-button type="primary" @click="makeAppointment(doctor)">
                  预约挂号 ¥{{ doctor.consultation_fee }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <div v-if="!loading && doctors.length === 0" class="no-doctors">
          <p>该科室暂无医生信息</p>
        </div>
      </section>

      <!-- 提示信息 -->
      <section v-if="!currentDepartment" class="tips-section">
        <el-card class="tips-card">
          <h3>预约挂号流程</h3>
          <div class="tips-content">
            <div class="tip-item">
              <div class="tip-number">1</div>
              <div class="tip-text">选择科室</div>
            </div>
            <div class="tip-item">
              <div class="tip-number">2</div>
              <div class="tip-text">选择医生</div>
            </div>
            <div class="tip-item">
              <div class="tip-number">3</div>
              <div class="tip-text">填写预约信息</div>
            </div>
            <div class="tip-item">
              <div class="tip-number">4</div>
              <div class="tip-text">确认预约</div>
            </div>
          </div>
        </el-card>
      </section>
    </main>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="预约挂号"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="appointmentForm" label-width="100px">
        <el-form-item label="医生信息">
          <div class="doctor-info-display">
            <img :src="selectedDoctor?.avatar" :alt="selectedDoctor?.name" class="doctor-avatar-small" />
            <div>
              <div class="doctor-name">{{ selectedDoctor?.name }}</div>
              <div class="doctor-title">{{ selectedDoctor?.title }} · {{ selectedDoctor?.department }}</div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="患者姓名" required>
          <el-input v-model="appointmentForm.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        
        <el-form-item label="联系电话" required>
          <el-input v-model="appointmentForm.patientPhone" placeholder="请输入联系电话" />
        </el-form-item>
        
        <el-form-item label="预约日期" required>
          <el-date-picker
            v-model="appointmentForm.appointmentDate"
            type="date"
            placeholder="选择预约日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="预约时间">
          <el-time-picker
            v-model="appointmentForm.appointmentTime"
            placeholder="选择预约时间"
            format="HH:mm"
            value-format="HH:mm"
          />
        </el-form-item>
        
        <el-form-item label="症状描述">
          <el-input
            v-model="appointmentForm.symptoms"
            type="textarea"
            :rows="3"
            placeholder="请描述您的症状"
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="appointmentForm.remarks"
            type="textarea"
            :rows="2"
            placeholder="其他需要说明的信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="appointmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppointment">确认预约</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.appointment-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 顶部导航栏 */
.header {
  background-color: #4CAF50;
  color: white;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  color: white !important;
  font-size: 16px;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.search-bar {
  flex: 1;
  max-width: 500px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 科室区域 */
.departments-section {
  margin-bottom: 40px;
}

.section-title {
  margin-bottom: 20px;
}

.section-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.section-title p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.section-subtitle {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.departments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.department-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  border: 2px solid transparent;
}

.department-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.department-item.active {
  border-color: #4CAF50;
  background-color: #f0f8f0;
}

.department-icon {
  font-size: 32px;
}

.department-info {
  display: flex;
  flex-direction: column;
}

.department-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.department-desc {
  font-size: 12px;
  color: #666;
}

/* 医生区域 */
.doctors-section {
  margin-bottom: 40px;
}

.doctors-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.doctor-card {
  transition: all 0.3s ease;
}

.doctor-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.doctor-avatar {
  text-align: center;
  margin-bottom: 15px;
}

.doctor-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.doctor-info {
  text-align: center;
}

.doctor-name {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.doctor-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #666;
}

.doctor-stats {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.doctor-specialties {
  margin-bottom: 15px;
}

.specialty-tag {
  display: inline-block;
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin: 2px;
}

.doctor-intro {
  margin-bottom: 15px;
}

.doctor-intro p {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin: 0;
}

.doctor-actions {
  margin-top: 15px;
}

.no-doctors {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 提示区域 */
.tips-section {
  margin-bottom: 40px;
}

.tips-card {
  text-align: center;
}

.tips-card h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.tips-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.tip-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.tip-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #4CAF50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 18px;
}

.tip-text {
  font-size: 14px;
  color: #666;
}

/* 预约对话框 */
.doctor-info-display {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.doctor-avatar-small {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }

  .search-bar {
    margin: 10px 0;
    max-width: 100%;
  }

  .departments-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .doctors-grid {
    grid-template-columns: 1fr;
  }

  .tips-content {
    flex-direction: column;
  }
}
</style>
